import {
  getMineCollectedProductListApi,
  getMinePublishedProductListApi,
  getMinePurchasedProductListApi,
  getMineSoldProductListApi,
} from '@/api/productInfo'
import { type Product } from '@/types/product'
import { useMineProductStore } from '@/stores/modules/mineProduct'
import { storeToRefs } from 'pinia'
import type { Result } from '@/types/result'
import { getUserOrderDataApi } from '@/api/productOrder'
import { ref } from 'vue'

// 定义 userOrderData 的类型
interface UserOrderDataType {
  purchased: string
  sold: string
  published: string
  collected: string
}

// 定义一个函数类型，用于接收一个当前页码和每页显示的商品数量，返回一个 Promise 结果
type ApiFunc = (currentPage: number, pageSize: number) => Promise<Result>

export default function () {
  const mineProductStore = useMineProductStore()
  const {
    publishedList,
    soldList,
    purchasedList,
    collectedList,
    hasMorePublished,
    hasMoreSold,
    hasMorePurchased,
    hasMoreCollected,
    publishedCurrentPage,
    soldCurrentPage,
    purchasedCurrentPage,
    collectedCurrentPage,
    pageSize,
  } = storeToRefs(mineProductStore)

  const userOrderData = ref<UserOrderDataType>()

  // 定义一个函数，用于获取商品列表
  const fetchProductList = async (
    apiFunc: ApiFunc,
    listRef: any,
    hasMoreRef: any,
    currentPageRef: any,
  ) => {
    if (!hasMoreRef.value) {
      ElMessage.warning('没有更多商品了')
      return
    }
    try {
      const res = await apiFunc(currentPageRef.value, pageSize.value)
      if (res.code === 0) {
        // 将图片地址字符串转换为数组
        const newProducts = res.data.records.map((item: Product) => ({
          ...item,
          image: item.image.split(',').map(url => url.replace(/^'|'$/g, '')),
        }))
        // 将新商品列表添加到已有商品列表中
        listRef.value = [...listRef.value, ...newProducts]
        if (newProducts.length < pageSize.value) {
          // 如果返回的商品数量小于每页显示的商品数量，则说明没有更多商品了
          hasMoreRef.value = false
          if (newProducts.length === 0 && currentPageRef.value === 1) {
            ElMessage.info('暂无数据')
          }
        } else {
          // 否则，页码加一
          currentPageRef.value++
        }
      } else {
        // 如果返回的 code 不为 0，说明出错了
        ElMessage.warning(res.msg || '获取数据失败')
        hasMoreRef.value = false
      }
    } catch (error) {
      console.error('获取数据失败:', error)
      ElMessage.error('获取数据失败')
      hasMoreRef.value = false
    }
  }

  // 根据商品发布者ID获取"已发布"商品列表
  const getMinePublishedProductList = () =>
    fetchProductList(
      getMinePublishedProductListApi,
      publishedList,
      hasMorePublished,
      publishedCurrentPage,
    )

  // 根据商品发布者ID获取"已卖出"商品列表
  const getMineSoldProductList = () =>
    fetchProductList(getMineSoldProductListApi, soldList, hasMoreSold, soldCurrentPage)

  // 根据商品发布者ID获取"已买到"商品列表
  const getMinePurchasedProductList = () =>
    fetchProductList(
      getMinePurchasedProductListApi,
      purchasedList,
      hasMorePurchased,
      purchasedCurrentPage,
    )

  // 根据商品发布者ID获取"已收藏"商品列表
  const getMineCollectedProductList = () =>
    fetchProductList(
      getMineCollectedProductListApi,
      collectedList,
      hasMoreCollected,
      collectedCurrentPage,
    )

  // 获取用户订单数据
  const getUserOrderData = async () => {
    const res = await getUserOrderDataApi()
    if (res.code === 0) {
      userOrderData.value = res.data
    } else {
      ElMessage.error(res.msg)
    }
  }

  return {
    userOrderData,
    getUserOrderData,
    getMinePublishedProductList,
    getMineSoldProductList,
    getMinePurchasedProductList,
    getMineCollectedProductList,
  }
}
